from odoo import http, api
from odoo.http import request, Response
import json


class ProductController(http.Controller):
    @http.route("/api/upsertProduct", auth="my_api_key", type="json", csrf=False, methods=["POST"])
    def upsert_product(self, **kwargs):
        data = request.jsonrequest
        existing_product = request.env['product.template'].sudo().search([('name', '=', data.get('name'))], limit=1)
        uom_id = request.env['uom.uom'].sudo().search([('name', 'ilike', data['product_unit'].upper())], limit=1)
        company_id = request.env['res.company'].sudo().search([('wos_company_id', '=', data['company_id'])], limit=1)
        x_product_type = request.env['product.category'].sudo().search([('code', '=', data['product_group'])], limit=1)
        print(company_id.name)
        if not uom_id:
            return {'status': 'error', 'data': 'Unit of Measure not found'}
        if not company_id:
            return {'status': 'error', 'data': 'Company not found'}
        if not x_product_type:
            return {'status': 'error', 'data': 'Product type category not found'}

        if data['charming_product_type'] not in ['product', 'materia', 'semi', 'consum', 'other']:
            return {'status': 'error', 'data': 'Product type is invalid'}

        agent = request.env['x.agent'].sudo().search([('name', '=', data['agent'].upper())], limit=1)
        product_brand = request.env['abk.brand'].sudo().search([('name', '=', data['product_brand'].upper())], limit=1)
        product_sub_brand = request.env['sub.brand'].sudo().search([('name', '=', data['product_sub_brand'].upper())],
                                                                   limit=1)
        product_data = {
            "name": data["name"],
            "company_id": company_id.id,
            "category_id": uom_id.category_id.id,
            "product_no": data["product_code"],
            "default_code": data["product_code"],
            "x_charming_product_type": data["charming_product_type"],
            'x_product_type': x_product_type.id,
            'categ_id': x_product_type.id,
            "sale_ok": True,
            "purchase_ok": True if data['name'][0] == 'F' else False,
            "uom_id": uom_id.id,
            "uom_po_id": uom_id.id,
            'charming_code': data["charming_code"],
            'x_agent': agent.id,
            'product_brand': product_brand.id,
            'product_sub_brand': product_sub_brand.id,
        }

        try:
            if existing_product:
                if existing_product.product_code != data["product_code"]:
                    return {'status': 'error', 'data': 'Updating the code is not allowed.'}
                pt = request.env["product.template"].with_user(23).browse(existing_product.id).write(product_data)
            else:
                pt = request.env["product.template"].with_user(23).create(product_data)
            if isinstance(data.get('bom'), list) and len(data['bom']) != 0:
                for y in data['bom']:
                    bom_data = {
                        'product_tmpl_id': pt.id,
                        'product_uom_id': uom_id.id,
                    }
                    bom = request.env['mrp.bom'].with_user(23).create(bom_data)
                    for x in y:
                        x_name = request.env['product.product'].sudo().search([('name', '=', x['product_name'])],
                                                                              limit=1)
                        uom_id = request.env['uom.uom'].sudo().search([('name', 'ilike', x['product_unit'].upper())],
                                                                      limit=1)
                        if not x_name:
                            # Rollback transaction if BOM product name does not exist
                            request.env.cr.rollback()
                            return {'status': 'error', 'data': 'BOM product name does not exist'}
                        bom_line_data = {
                            'bom_id': bom.id,
                            'product_id': x_name.id,
                            'product_uom_id': uom_id.id,
                            'product_qty': x['quantity'],
                            'abk_scrap': x['scrap'] if 'scrap' in x and x['scrap'] else '',
                            'x_ups': x['ups'] if 'ups' in x and x['ups'] else '',
                            'x_sheet_cut': x['sheet_cut'] if 'sheet_cut' in x and x['sheet_cut'] else '',
                            'x_pick_rate': x['pick_rate'] if x.get('pick_rate') else '',
                            'x_denier': x['denier'] if x.get('denier') else '',
                        }
                        request.env['mrp.bom.line'].with_user(23).create(bom_line_data)

            request.env.cr.commit()

        except Exception as e:
            # 事务回滚
            request.env.cr.rollback()
            return {'status': 'error', 'data': str(e)}

        return {'status': 'success', 'data': 'Product created successfully'}
